import axios from 'axios'
import { Toast } from 'mint-ui'
let baseUrl = 'http://dev.fastsun.com.cn:8060'

const request = axios.create({
  baseUrl,
  timeout: 50000
})

request.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json;charset=UTF-8'
    return config
  }, error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    let {code, message} = response.data
    if (code && code !== '1') {
      Toast(message)
    }
    return Promise.resolve(response.data)
  }, error => {
    Toast('系统异常, 请稍后重试')
    return Promise.reject(error)
  }
)

export function get (url, params) {
  return new Promise((resolve, reject) => {
    request.get(baseUrl + url, {
      params: params
    }).then(res => {
      console.log(res)
      const {code, data, msg} = res
      if (code === '1') {
        resolve(data || [])
      } else {
        Toast(msg)
        resolve(false)
      }
    }).catch(error => {
      Toast('服务器内部错误！')
      resolve(false)
    })
  })
}

export function post (url, params) {
  return new Promise((resolve, reject) => {
    request.post(baseUrl + url, params)
      .then(res => {
        const {code, data, msg} = res
        if (code === '1') {
          resolve(data)
        } else {
          Toast(msg)
          resolve(false)
        }
      }).catch(err => {
        Toast('服务器内部错误！')
        resolve(false)
      })
  })
}

export function deleteFunc (url, params) {
  return new Promise((resolve, reject) => {
    request.delete(baseUrl + url, params)
      .then(res => {
        const {code, data, msg} = res.data
        if (code === '1') {
          resolve(data)
        } else {
          Toast(msg)
          resolve(false)
        }
      }).catch(err => {
        Toast('服务器内部错误！')
        resolve(false)
      })
  })
}

export default request
